package rpcm

import (
	"fmt"
	"github.com/chenwbyx/leafserver/server/models"
	"github.com/jinzhu/gorm"
)

type AccountInfo struct {
	UserID   int    `gorm:"primary_key;not null;index:name_idx;AUTO_INCREMENT"`
	UserName string `gorm:"ype:varchar(256);not null;unique"`
	Password string
	models.Model
}

// CheckAuth checks if authentication information exists
func GetLoginByName(username string) (bool, error) {
	var auth AccountInfo
	err := models.Db.Select("user_id").Where(AccountInfo{UserName: username}).First(&auth).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	if auth.UserID > 0 {
		return true, nil
	}
	return false, nil
}

func GetAccountByName(accountName string) *AccountInfo {
	var account AccountInfo
	// gorm的database

	// db.DropTableIfExists(&Account{})
	if rs := models.Db.HasTable(&AccountInfo{}); !rs {
		models.Db.AutoMigrate(&AccountInfo{})
	}
	err := models.Db.Where("user_name = ?", accountName).Limit(1).Find(&account).Error
	if nil != err {
		fmt.Println(err)
		return nil
	}
	fmt.Println("password:", account.Password)
	return &account
}

// 创建账号名存储在数据库
func CreatAccountByAccountIDAndPassword(accountName string, password string) *AccountInfo {
	// db.DropTableIfExists(&Account{})
	if rs := models.Db.HasTable(&AccountInfo{}); !rs {
		models.Db.AutoMigrate(&AccountInfo{})
	}
	var account = AccountInfo{UserName: accountName, Password: password}
	err := models.Db.Create(&account).Error
	if nil != err {
		return nil
	}
	return &account
}

func CheckLogin(username, password string) (bool, error) {
	var auth AccountInfo
	err := models.Db.Select("user_id").Where(AccountInfo{UserName: username, Password: password}).First(&auth).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	if auth.UserID > 0 {
		return true, nil
	}
	return false, nil
}

// AddTag Add a Login
func AddLogin(username, password string) error {
	login := AccountInfo{
		UserName: username,
		Password: password,
	}
	if err := models.Db.Create(&login).Error; err != nil {
		return err
	}
	return nil
}
